package development;

import iplayparticle.view.iplayparticleResources;
import state.DrawListener;
import state.GameAlert;
import state.GameControl;
import state.GameForm;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.SMSHandler;
import state.SendSMSListener;
import state.Sprite;
import state.TouchScreenListener;
import state.component.Event;
import state.component.EventListener;
import state.component.MultiTab;
import state.component.TextField;
import state.font.FontManager;
import state.font.ImageFont;
import state.socket.DataPackage;
import state.util.GameColor;
import state.util.Hashtable;
import state.util.ImageUtil;
import state.util.array.StringArray;
import development.group.FrmGroup18Plus;
import development.group.FrmGroupCuaHang18PlusNapXu;
import development.group.FrmGroupNapXuAndExchangeGold;
import development.socket.ProtocolConstants;

public class FrmNapXu extends GameForm implements SendSMSListener, EventListener, TouchScreenListener {
  private int LIST_DX;
  private int LIST_TEXT_DX;
  private int LIST_DY;
  private int LIST_WIDTH;
  private int LIST_VER_DIS;

  private int INFO_BOX_DY;

  private final int INFO_BOX_WIDTH = 176;

  private GameImage coinIconImage;
  private GameImage buttonImage;

  private int currentRow;
  private boolean isShowInfoBox;
  private boolean isShowInputSerialBox;
  private int serialBoxIndex;

  private StringArray napXuTexts;
  private StringArray cardTypes;
  private StringArray infoTexts;

  private TextField serialTextField;
  private TextField maCaoTextField;
  private Sprite confirmButtonSprite;

  private ImageFont text11;
  private ImageFont text8;

  private Hashtable parameters;
  String vimobResponse;
  
  private static GameForm singleton;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmNapXu();
    }
    return singleton;
  }

  public void init(Hashtable parameters1) {
    this.parameters = parameters1;
    coinIconImage = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "icon_Nap-xu.png");
    buttonImage = new GameImage(iplayparticleResources.image_button, null, null);

    serialTextField = new TextField(_manager, TextField.CONSTRAINT_ANY, Constants.TEXT_FIELD_STYLE);
    serialTextField.setSize(122, 20);
    serialTextField.setFocused(true);
    serialTextField.setVisible(false);
    maCaoTextField = new TextField(_manager, TextField.CONSTRAINT_NUMERIC, Constants.TEXT_FIELD_STYLE);
    maCaoTextField.setSize(122, 20);
    maCaoTextField.setVisible(false);

    if (Constants.IS_240x320_SCREEN) {
      LIST_DX = 5;
      LIST_TEXT_DX = 37;
      LIST_DY = 33;
      LIST_WIDTH = 287;
      LIST_VER_DIS = 26;

      INFO_BOX_DY = 109;
      serialTextField.setPosition(82, 133);
      maCaoTextField.setPosition(82, 159);
      confirmButtonSprite = new Sprite(buttonImage, _manager, Constants.SCREEN_WIDTH / 2, 185, Constants.TOP_HCENTER_ANCHOR);
    } else {
      LIST_DX = 5;
      LIST_TEXT_DX = 24;
      LIST_DY = 33;
      LIST_WIDTH = 308;
      LIST_VER_DIS = 20;

      INFO_BOX_DY = 55;
      serialTextField.setPosition(121, 85);
      maCaoTextField.setPosition(121, 111);
      confirmButtonSprite = new Sprite(buttonImage, _manager, 90, 135, Constants.TOP_LEFT_ANCHOR);
    }

    confirmButtonSprite.setVisible(false);
    confirmButtonSprite.setTouchScreenListener(this);
    confirmButtonSprite.setDrawListener(new DrawListener() {
      public void paint(Sprite source, Graphics g) {
        if (serialBoxIndex == 2) {
          text8.drawString2(g, "Xác nhận", GameColor.YELLOW_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
        } else {
          text8.drawString2(g, "Xác nhận", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
        }
      }

    });

    currentRow = 0;
    isShowInfoBox = false;
    isShowInputSerialBox = false;
    serialBoxIndex = 0;

    if (napXuTexts == null) {
      napXuTexts = StringArray.create(8);
      napXuTexts.array[0] = "Nạp 15000 (SMS 15K)";
      napXuTexts.array[1] = "Nạp 10000 (SMS 10K)";
      napXuTexts.array[2] = "Thẻ Mobifone (x2)";
      napXuTexts.array[3] = "Thẻ Viettel (x2)";
      napXuTexts.array[4] = "Thẻ Vinaphone (x2)";
      napXuTexts.array[5] = "Thẻ FPT-Gate (x2)";
      napXuTexts.array[6] = "Thẻ VTC-VCoin (x2)";
      napXuTexts.array[7] = "Đổi gold";
      cardTypes = new StringArray(new String[] { "", "", "VMS", "VIETTEL", "VNP", "GATE", "VCOIN" },7);
    }

    if (infoTexts == null) {
      infoTexts = StringArray.create(5);
      infoTexts.array[0] = "10K -> x2 = 20K";
      infoTexts.array[1] = "20K -> x2 = 40K";
      infoTexts.array[2] = "30K -> x2 = 60K";
      infoTexts.array[3] = "40K -> x2 = 80K";
      infoTexts.array[4] = "50K -> x2 = 100K";
    }

    text11 = FontManager.getFont(FontManager.FONT_SIZE_11);
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    _manager.enableTouchPad();
    // string result from vimob
  }
  
  private void drawInfoBox(Graphics g) {
    int x = (Constants.SCREEN_WIDTH - INFO_BOX_WIDTH) / 2;

    g.setColor(0x5B0707);
    g.fillRect(x, INFO_BOX_DY, INFO_BOX_WIDTH, 21);

    g.setColor(0xA54D4C);
    g.fillRect(x, INFO_BOX_DY + 21, INFO_BOX_WIDTH, 86);

    g.setColor(GameColor.WHITE_CODE);
    g.drawRect(x, INFO_BOX_DY, INFO_BOX_WIDTH, 107);
  }

  public void draw(Graphics g) {
    DrawUtils.drawBackground(g);
    for (int i = 0; i < napXuTexts.len(); i++) {
      int rowY = LIST_DY + i * LIST_VER_DIS;

      if (i == currentRow) {
        g.setColor(GameColor.WHITE_CODE);
        g.fillRect(LIST_DX, rowY, LIST_WIDTH, LIST_VER_DIS);
        g.drawImage(coinIconImage, LIST_DX, rowY + LIST_VER_DIS / 2, Constants.VCENTER_LEFT_ANCHOR);
        text8.drawString2(g, String.valueOf(napXuTexts.array[i]), 0x05BB5D, LIST_TEXT_DX, rowY + LIST_VER_DIS / 2, Constants.VCENTER_LEFT_ANCHOR);
      } else {
        g.drawImage(coinIconImage, LIST_DX, rowY + LIST_VER_DIS / 2, Constants.VCENTER_LEFT_ANCHOR);
        text8.drawString2(g, String.valueOf(napXuTexts.array[i]), GameColor.WHITE_CODE, LIST_TEXT_DX, rowY + LIST_VER_DIS / 2, Constants.VCENTER_LEFT_ANCHOR);
      }
      g.setColor(GameColor.WHITE_CODE);
      g.drawLine(LIST_DX, rowY, LIST_DX + LIST_WIDTH, rowY);
    }

    if (isShowInfoBox) {
      drawInfoBox(g);
      text11.drawString2(g, "HỆ THỐNG", GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2, INFO_BOX_DY + 3, Constants.TOP_HCENTER_ANCHOR);
      text11.drawString2(g, "<<", GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2 - 70, INFO_BOX_DY + 3, Constants.TOP_HCENTER_ANCHOR);
      text11.drawString2(g, ">>", GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2 + 70, INFO_BOX_DY + 3, Constants.TOP_HCENTER_ANCHOR);
      for (int i = 0; i < infoTexts.len(); i++) {
        text8.drawString1(g, infoTexts.array[i], Constants.SCREEN_WIDTH / 2 - 45, INFO_BOX_DY + 28 + 17 * i, Constants.TOP_LEFT_ANCHOR);
      }
    }

    if (isShowInputSerialBox) {
      drawInfoBox(g);
      text11.drawString2(g, napXuTexts.array[currentRow], GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2, INFO_BOX_DY + 1, Constants.TOP_HCENTER_ANCHOR);

      serialTextField.draw(g);
      maCaoTextField.draw(g);
      if (Constants.IS_240x320_SCREEN) {
        text8.drawString2(g, "Số Seri", GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2 - 81, 132, Constants.TOP_LEFT_ANCHOR);
        text8.drawString2(g, "Mã cào", GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2 - 81, 158, Constants.TOP_LEFT_ANCHOR);
      } else {
        text8.drawString2(g, "Số Seri", GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2 - 81, 85, Constants.TOP_LEFT_ANCHOR);
        text8.drawString2(g, "Mã cào", GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2 - 81, 111, Constants.TOP_LEFT_ANCHOR);
      }
      DrawUtils.setBottomBar(_manager, "Hủy", "Chọn", "Trở về");
    } else {
      DrawUtils.setBottomBar(_manager, "", "Chọn", "Trở về");
    }
  }

  public void updateFocus() {
    serialTextField.setFocused(false);
    maCaoTextField.setFocused(false);
    if (serialBoxIndex == 0) {
      serialTextField.setFocused(true);
      DrawUtils.setBottomBar(_manager, "Hủy", "", "Xóa");
    } else if (serialBoxIndex == 1) {
      maCaoTextField.setFocused(true);
      DrawUtils.setBottomBar(_manager, "Hủy", "", "Xóa");
    }
  }
  
  public void onActionPerform(Event event) {
    if (MultiTab.OPEN_TAB_EVENT.equals(event.getAction())) {
      DrawUtils.setBottomBar(_manager, "", "Chọn", "Trở về");
      return;
    }
  }

  public void keyReleased(int keyCode) {
    if (keyCode == Key.SOFT_RIGHT) {
      if (isShowInfoBox) {
        isShowInfoBox = false;
      } else if (isShowInputSerialBox) {
        if (serialBoxIndex == 0) {
          serialTextField.deleteLastChar();
        } else if (serialBoxIndex == 1) {
          maCaoTextField.deleteLastChar();
        }
      } else {
        parentGroup.goBack();
      }
      return;
    }

    if (isShowInfoBox) {
      return;
    }

    if (isShowInputSerialBox) {
      switch (keyCode) {
      case Key.UP:
        serialBoxIndex = --serialBoxIndex < 0 ? 0 : serialBoxIndex;
        updateFocus();
        break;
      case Key.DOWN:
        serialBoxIndex = ++serialBoxIndex > 2 ? 2 : serialBoxIndex;
        updateFocus();
        break;
      case Key.FIRE:
        if (serialBoxIndex == 0) {
          serialTextField.pointerReleased(serialTextField, serialTextField.getRealX(), serialTextField.getRealY());
        } else if (serialBoxIndex == 1) {
          maCaoTextField.pointerReleased(maCaoTextField, maCaoTextField.getRealX(), maCaoTextField.getRealY());
        } else if (serialBoxIndex == 2) {
          if (serialTextField.getText().length() == 0 || maCaoTextField.getText().length() == 0) {
            Global.alert.showAlert(this, GameAlert.OK_TYPE, "Hãy nhập đủ thông tin");
            return;
          }
          isShowInputSerialBox = false;
          serialTextField.setVisible(false);
          maCaoTextField.setVisible(false);
          confirmButtonSprite.setVisible(false);
          if (Global.provider.getId() == Constants.TINHVAN_PROVIDER_ID) {// game clien cua tinh van
            // lay provider tu file xas.conf
            new GameControl() {
              public void perform() {
                postParamsToURL(cardTypes.array[currentRow], serialTextField.getText(), maCaoTextField.getText());
              }
            }.start();
          } else if (Global.provider.getId() == Constants.HDC_PROVIDER_ID) {
            DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.COIN_CHARGING_REQUEST);
            dataPackage.putString(Global.currentUser.getName());
            dataPackage.putString(cardTypes.array[currentRow]);
            dataPackage.putString(serialTextField.getText());
            dataPackage.putString(maCaoTextField.getText());
            dataPackage.putString(Constants.CARD_SECURE_KEY); // partner id ( ref code )
            dataPackage.putString(Constants.HDC_PROVIDER_ID + ""); // channel id
            Global.authenClient.write(dataPackage);
          } else { // game client ko phai cua tinh van
            DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.COIN_CHARGING_REQUEST);
            dataPackage.putString(Global.currentUser.getName());
            dataPackage.putString(cardTypes.array[currentRow]);
            dataPackage.putString(serialTextField.getText());
            dataPackage.putString(maCaoTextField.getText());
            Global.authenClient.write(dataPackage);
          }
        }
        break;
      case Key.SOFT_LEFT:
        isShowInputSerialBox = false;
        serialTextField.setVisible(false);
        maCaoTextField.setVisible(false);
        confirmButtonSprite.setVisible(false);
        break;
      default:
        if (serialBoxIndex == 0) {
          serialTextField.keyReleased1(keyCode);
        } else if (serialBoxIndex == 1) {
          maCaoTextField.keyReleased1(keyCode);
        }
        break;
      }
      return;
    }

    switch (keyCode) {
    case Key.LEFT:
      if (Global.systemCanvas.frmCurrent == FrmGroup18Plus.instance()) {
        FrmGroup18Plus.setTab(1);
      } else if (Global.systemCanvas.frmCurrent == FrmGroupCuaHang18PlusNapXu.instance()) {
        FrmGroupCuaHang18PlusNapXu.setTab(1);
      }
      break;
    case Key.UP:
      currentRow = --currentRow < 0 ? napXuTexts.len() - 1 : currentRow;
      break;
    case Key.DOWN:
      currentRow = (currentRow + 1) % napXuTexts.len();
      break;
    case Key.FIRE:
      StringBuffer sb = new StringBuffer();
      String[] sms = null;
      switch (currentRow) {
      case 0:
        // 7x85
        sms = (String[]) Global.smsCommand.get("GAME_NAP_15K");
        // 9x79
        // sms = (String[]) Global.smsCommand.get("GAME_NAP_VIETTEL_15K");
        sb.append(sms[0]);
        sb.append(" ");
        sb.append(Global.currentUser.getName());
        sb.append(" ");
        sb.append(Global.provider.getId());
        if (Global.provider.getId() == Constants.TINHVAN_PROVIDER_ID) {
          SMSHandler.getInstance(this).sendMsg(sms[1], Constants.SMS_PREFIX + " " + sb.toString());
        } else if (Global.provider.getId() == Constants.HDC_PROVIDER_ID) {
          SMSHandler.getInstance(this).sendMsg(sms[1], sb.toString() + " " + Constants.CARD_SECURE_KEY);
        } else {
          
          SMSHandler.getInstance(this).sendMsg(sms[1], sb.toString());
        }
        break;
      case 1:
        // 7x85
        sms = (String[]) Global.smsCommand.get("GAME_NAP_10K");
        // 9x79
        // sms = (String[]) Global.smsCommand.get("GAME_NAP_VIETTEL_10K");
        sb.append(sms[0]);
        sb.append(" ");
        sb.append(Global.currentUser.getName());
        sb.append(" ");
        sb.append(Global.provider.getId());
        if (Global.provider.getId() == Constants.TINHVAN_PROVIDER_ID) {
          SMSHandler.getInstance(this).sendMsg(sms[1], Constants.SMS_PREFIX + " " + sb.toString());
        } else if (Global.provider.getId() == Constants.HDC_PROVIDER_ID) {
          SMSHandler.getInstance(this).sendMsg(sms[1], sb.toString() + " " + Constants.CARD_SECURE_KEY);
        } else {
          SMSHandler.getInstance(this).sendMsg(sms[1], sb.toString());
        }
        break;
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
        isShowInputSerialBox = true;
        serialTextField.clearText();
        maCaoTextField.clearText();
        serialTextField.setVisible(true);
        maCaoTextField.setVisible(true);
        confirmButtonSprite.setVisible(true);
        break;
      case 7:
        if (Global.systemCanvas.frmCurrent != FrmGroupNapXuAndExchangeGold.instance()) {
          Global.nextState(FrmGroupNapXuAndExchangeGold.instance(), null);
        }
        FrmGroupNapXuAndExchangeGold.setTab(1);
        break;
      default:
        break;
      }
      break;
    }
  }

  public void onSendSMSFail() {
    Global.alert.showAlert(this, GameAlert.OK_TYPE, "Gửi tin nhắn thất bại");
  }

  public void onSendSMSSuccess() {
    Global.alert.showAlert(this, GameAlert.OK_TYPE, "Gửi tin nhắn thành công");
  }

  public void destroy() {
    coinIconImage = null;
    buttonImage = null;

    napXuTexts = null;
    cardTypes = null;
    infoTexts = null;

    serialTextField = null;
    maCaoTextField = null;
    confirmButtonSprite = null;

    text11 = null;
    text8 = null;

    parameters = null;
    vimobResponse = null;
  }

  public void postParamsToURL(final String provider, final String serial, final String pin) {
//    String[] providers = GameStringUtils.split(Constants.CARD_PROVIDERS.trim(), "|");
//    String provided = "viettel";
//    // mobi|viettel|vina|vtc|fpt
//    Hashtable provi = new Hashtable();
//    for (int i = 0; i < providers.length; i++) {
//      if (providers[i].equalsIgnoreCase("mobi")) {
//        provi.put("VMS", "mobi");
//      }
//      if (providers[i].equalsIgnoreCase("viettel")) {
//        provi.put("VIETTEL", "viettel");
//      }
//      if (providers[i].equalsIgnoreCase("vina")) {
//        provi.put("VNP", "vina");
//      }
//      if (providers[i].equalsIgnoreCase("vtc")) {
//        provi.put("VCOIN", "vtc");
//      }
//      if (providers[i].equalsIgnoreCase("fpt")) {
//        provi.put("GATE", "fpt");
//      }
//    }
//
//    // mobi|viettel|vina|vtc|fpt
//    if (provider.equalsIgnoreCase("VMS")) {
//      provided = provi.get("VMS").toString();
//    } else if (provider.equalsIgnoreCase("VIETTEL")) {
//      provided = provi.get("VIETTEL").toString();
//    } else if (provider.equalsIgnoreCase("VNP")) {
//      provided = provi.get("VNP").toString();
//    } else if (provider.equalsIgnoreCase("VCOIN")) {
//      provided = provi.get("VCOIN").toString();
//    } else if (provider.equalsIgnoreCase("GATE")) {
//      provided = provi.get("GATE").toString();
//    }
//
//    String url = Constants.CARD_URL;
//    InputStream istrm = null;
//    OutputStreamWriter out = null;
//    String time, cardSecureKey, secureKey;
//    String id = "";
//    String status = "";
//    String message = "";
//    String value = "";
//    String userMessage = "";
//    java.util.Date date = new java.util.Date();
//    Calendar calendar = Calendar.getInstance();
//    calendar.setTime(date);
//    int year = calendar.get(Calendar.YEAR);
//    int month = calendar.get(Calendar.MONTH);
//    int day = calendar.get(Calendar.DAY_OF_MONTH);
//    int hour = calendar.get(Calendar.HOUR_OF_DAY);
//    int minute = calendar.get(Calendar.MINUTE);
//    int second = calendar.get(Calendar.SECOND);
//    time = year + "-" + (month < 10 ? "0" + month : month + "") + "-" + (day < 10 ? "0" + day : day + "") + " " + (hour < 10 ? "0" + hour : hour + "") + ":"
//        + (minute < 10 ? "0" + minute : minute + "") + ":" + (second < 10 ? "0" + second : second + "");
//
//    cardSecureKey = Constants.CARD_SECURE_KEY;
//    secureKey = (provided + "|" + serial + "|" + pin + "|" + Global.currentUser.getName() + "|" + time + "|" + cardSecureKey + "|" + Constants.APIKEY);
//    MD5 md5 = new MD5(secureKey.getBytes());
//    byte[] result = md5.doFinal();
//    secureKey = MD5.toHex(result);
//    String params = "&card[provider]=" + provided;
//    params += "&card[serial]=" + serial;
//    params += "&card[pin]=" + pin;
//    params += "&card[account]=" + Global.currentUser.getName();
//    params += "&card[time]=" + time;
//    params += "&card[cardSecureKey]=" + cardSecureKey;
//    params += "&card[secureKey]=" + secureKey;
//    
//    // Send request
//    HTTP httpConn = HTTP.newHTTP();
//    URI uri = new URI();
//    uri.parse(url);
//    httpConn.setURI(uri);
//    httpConn.setMethod(HTTP.MethodPost);
//    httpConn.addRequestHeader("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
//    httpConn.addRequestHeader("Accept_Language", "en-US");
//    httpConn.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//    
//    // TODO: request HTTP khi nạp xu
//    
//    ByteBuffer requestDataBuffer = new ByteBuffer();
//    requestDataBuffer.appendString(params.toString(), ByteBuffer.EncodingUTF8);
//    httpConn.sendRequest(requestDataBuffer);
//    
//    istrm = httpConn.openDataInputStream();
//    byte[] readData = new byte[istrm.available()];
//    int actual = istrm.read(readData);
//
//    vimobResponse = new String(readData, 0, actual, "UTF-8");
//    vimobResponse = vimobResponse.toString().trim();
//    vimobResponse = GameStringUtils.replaceAll(vimobResponse, "{", "");
//    vimobResponse = GameStringUtils.replaceAll(vimobResponse, "}", "");
//    vimobResponse = GameStringUtils.replaceAll(vimobResponse, "\"", "");
//    String[] arrResponse = GameStringUtils.split(vimobResponse, ",");
//
//    for (int i = 0; i < arrResponse.length; i++) {
//      String[] arr = GameStringUtils.split(arrResponse[i], ":");
//      if (arr[0].equalsIgnoreCase("id")) {
//        id = arr[1];
//      }
//      if (arr[0].equalsIgnoreCase("status")) {
//        status = arr[1];
//      }
//      if (arr[0].equalsIgnoreCase("message")) {
//        message = arr[1];
//      }
//      if (arr[0].equalsIgnoreCase("value")) {
//        value = arr[1];
//      }
//      if (arr[0].equalsIgnoreCase("userMessage")) {
//        userMessage = arr[1];
//      }
//    }
//    if (status.equalsIgnoreCase("0")) {
//      DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.COIN_VIMOB_CHARGING_REQUEST);
//      dataPackage.putString(Global.currentUser.getName());
//      dataPackage.putInt(NumberUtil.parseInt(status));
//      dataPackage.putString(value);
//      dataPackage.putString(id);
//      dataPackage.putString(Global.provider.getId() + "");
//      Global.authenClient.write(dataPackage);
//      Global.alert.showAlert(this, GameAlert.OK_TYPE, GameStringUtils.split(userMessage, "."));
//    } else {
//      Global.alert.showAlert(this, GameAlert.OK_TYPE, GameStringUtils.split(message + "." + userMessage, "."));
//    }
  }

  public void pointerDragged(Sprite source, int x, int y) {
  }

  public void pointerPressed(Sprite source, int x, int y) {
  }

  public void pointerReleased(Sprite source, int x, int y) {
    if (confirmButtonSprite == source) {
      serialBoxIndex = 2;
      updateFocus();
      keyReleased(Key.FIRE);
    }
  }
}
